import { defineConfig } from 'vite' 
import uni from '@dcloudio/vite-plugin-uni';
import { resolve } from 'path';
// 读取 manifest.json ，修改后重新写入
const fs = require('fs');

const manifestPath = process.env.UNI_INPUT_DIR + '/manifest.json'
let Manifest = fs.readFileSync(manifestPath, { encoding: 'utf-8' });
function replaceManifest(path, value) {
  const arr = path.split('.')
  const len = arr.length
  const lastItem = arr[len - 1]

  let i = 0
  let ManifestArr = Manifest.split(/\n/)

  for (let index = 0; index < ManifestArr.length; index++) {
    const item = ManifestArr[index]
    if (new RegExp(`"${arr[i]}"`).test(item)) ++i;
    if (i === len) {
      const hasComma = /,/.test(item)
      ManifestArr[index] = item.replace(
		new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`),
		`"${lastItem}": "${value}"${hasComma ? ',' : ''}`
	  );
      break;
    }
  }

  Manifest = ManifestArr.join('\n')
}

// 动态调整appid
if(process.env.UNI_CUSTOM_SCRIPT === 'mp-zyx'){
	replaceManifest('mp-weixin.appid',"wx554f86dfa21d0373");
}else if(process.env.UNI_CUSTOM_SCRIPT === 'mp-yhdd'){
	replaceManifest('mp-weixin.appid',"wx0abc058a59e4caff");
}else if(process.env.UNI_CUSTOM_SCRIPT === 'mp-ydyx'){
	replaceManifest('mp-weixin.appid',"wxdb0d7deb4427d9ed");
}else{
	replaceManifest('mp-weixin.appid',"wx2b9f9a4a9bb193e0");
}

fs.writeFileSync(manifestPath, Manifest, {
	flag: 'w',
});

export default ({ mode }) => {
	return defineConfig({
		resolve: {
			alias: {
				'@': resolve(__dirname, '')
			}
		},
		plugins: [uni()],
		build: {
			terserOptions: {
				compress: {
					drop_console: true,	// 发布时删除
				}
			},
		},
	})
}
